using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Search;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Threading.Tasks;
using DocumentCreationSystem.Services;
using MaterialDesignThemes.Wpf;
using System.Windows.Media;

namespace DocumentCreationSystem.Controls
{
    /// <summary>
    /// DocumentEditor.xaml 的交互逻辑
    /// </summary>
    public partial class DocumentEditor : UserControl
    {
        private SearchPanel? _searchPanel;
        private int _lastFindIndex = 0;
        private string? _currentFilePath;
        private string? _currentProjectPath;
        private bool _isModified = false;
        private IVectorService? _vectorService;
        private IDocumentService? _documentService;
        private ISystemMonitorService? _systemMonitorService;
        private IAIService? _aiService;
        private System.Windows.Threading.DispatcherTimer? _statusUpdateTimer;

        // 增强的章节重写事件
        public event EventHandler<Models.EnhancedChapterRewriteEventArgs>? EnhancedChapterRewriteRequested;

        public event EventHandler<TextChangedEventArgs>? DocumentTextChanged;
        public event EventHandler<SelectionChangedEventArgs>? DocumentSelectionChanged;
        public event EventHandler<DocumentSavedEventArgs>? DocumentSaved;

        public DocumentEditor()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始初始化DocumentEditor...");
                InitializeComponent();
                System.Diagnostics.Debug.WriteLine("InitializeComponent完成");

                // 延迟初始化编辑器，等待控件完全加载
                Loaded += DocumentEditor_Loaded;
                System.Diagnostics.Debug.WriteLine("DocumentEditor构造函数完成");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"DocumentEditor构造函数失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    System.Diagnostics.Debug.WriteLine($"内部异常: {ex.InnerException.Message}");
                    System.Diagnostics.Debug.WriteLine($"内部异常堆栈: {ex.InnerException.StackTrace}");
                }
                // 重新抛出异常，让调用者知道初始化失败
                throw new InvalidOperationException($"DocumentEditor初始化失败: {ex.Message}", ex);
            }
        }

        private void DocumentEditor_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                InitializeEditor();
                // 确保主题正确应用
                ApplyCurrentTheme();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"DocumentEditor延迟初始化失败: {ex.Message}");
                // 在Loaded事件中不抛出异常，避免崩溃
            }
        }

        /// <summary>
        /// 设置服务依赖
        /// </summary>
        public void SetServices(IVectorService vectorService, IDocumentService documentService,
                                ISystemMonitorService? systemMonitorService = null, IAIService? aiService = null)
        {
            _vectorService = vectorService;
            _documentService = documentService;
            _systemMonitorService = systemMonitorService;
            _aiService = aiService;

            // 初始化状态更新定时器
            InitializeStatusTimer();
        }

        /// <summary>
        /// 当前文件路径
        /// </summary>
        public string? CurrentFilePath
        {
            get => _currentFilePath;
            set
            {
                _currentFilePath = value;
                _isModified = false;
                UpdateTitle();
            }
        }

        /// <summary>
        /// 当前项目路径
        /// </summary>
        public string? CurrentProjectPath
        {
            get => _currentProjectPath;
            set => _currentProjectPath = value;
        }

        /// <summary>
        /// 文档是否已修改
        /// </summary>
        public bool IsModified
        {
            get => _isModified;
            private set
            {
                _isModified = value;
                UpdateTitle();
            }
        }

        /// <summary>
        /// 设置文档修改状态
        /// </summary>
        /// <param name="modified">是否已修改</param>
        public void SetModified(bool modified)
        {
            IsModified = modified;
        }

        private void InitializeEditor()
        {
            try
            {
                // 检查TextEditor是否已初始化
                if (TextEditor == null)
                {
                    System.Diagnostics.Debug.WriteLine("TextEditor控件为null，跳过初始化");
                    return;
                }

                // 检查TextEditor是否已经加载
                if (!TextEditor.IsLoaded)
                {
                    System.Diagnostics.Debug.WriteLine("TextEditor控件尚未加载，跳过初始化");
                    return;
                }

                // 安装搜索面板
                try
                {
                    _searchPanel = SearchPanel.Install(TextEditor);
                }
                catch (Exception searchEx)
                {
                    System.Diagnostics.Debug.WriteLine($"搜索面板安装失败: {searchEx.Message}");
                    // 搜索面板安装失败不应该阻止编辑器工作
                }

                // 设置默认文本
                try
                {
                    TextEditor.Text = "欢迎使用文档管理及AI创作系统！\n\n您可以在这里开始创作您的文档或小说。\n\n功能特色：\n• AI辅助创作\n• 智能润色\n• 内容扩写\n• 一致性检查\n• 向量搜索\n\n开始您的创作之旅吧！";
                }
                catch (Exception textEx)
                {
                    System.Diagnostics.Debug.WriteLine($"设置默认文本失败: {textEx.Message}");
                    // 尝试设置简单文本
                    try
                    {
                        TextEditor.Text = "编辑器已就绪";
                    }
                    catch
                    {
                        // 如果连简单文本都设置不了，就放弃
                    }
                }

                // 更新字数统计
                try
                {
                    UpdateWordCount();
                }
                catch (Exception countEx)
                {
                    System.Diagnostics.Debug.WriteLine($"更新字数统计失败: {countEx.Message}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"DocumentEditor初始化失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
            }
        }

        public string Text
        {
            get => TextEditor?.Text ?? string.Empty;
            set
            {
                if (TextEditor != null)
                    TextEditor.Text = value ?? string.Empty;
            }
        }

        public string SelectedText
        {
            get => TextEditor?.SelectedText ?? string.Empty;
            set
            {
                if (TextEditor != null)
                    TextEditor.SelectedText = value ?? string.Empty;
            }
        }

        public bool HasSelection => !string.IsNullOrEmpty(TextEditor?.SelectedText);

        private void TextEditor_TextChanged(object? sender, EventArgs e)
        {
            UpdateWordCount();
            IsModified = true;
            DocumentTextChanged?.Invoke(this, new TextChangedEventArgs());
        }

        private void TextEditor_SelectionChanged(object? sender, EventArgs e)
        {
            DocumentSelectionChanged?.Invoke(this, new SelectionChangedEventArgs());
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            // 手动绑定SelectionChanged事件，因为XAML中无法直接绑定
            if (TextEditor?.TextArea != null)
            {
                TextEditor.TextArea.SelectionChanged += TextEditor_SelectionChanged;
            }

            // 绑定键盘快捷键
            this.KeyDown += DocumentEditor_KeyDown;

            // 初始化主题
            ApplyCurrentTheme();
        }

        /// <summary>
        /// 应用当前主题到编辑器
        /// </summary>
        private void ApplyCurrentTheme()
        {
            if (TextEditor == null) return;

            try
            {
                var paletteHelper = new PaletteHelper();
                var theme = paletteHelper.GetTheme();

                // 设置编辑器背景色
                var backgroundColor = new SolidColorBrush(theme.Background);
                TextEditor.Background = backgroundColor;

                // 设置编辑器前景色（文字颜色）
                var foregroundColor = new SolidColorBrush(theme.Body);
                TextEditor.Foreground = foregroundColor;

                // 设置行号颜色（简化处理，避免复杂的类型转换）
                // 行号颜色会通过主题自动调整

                // 设置选择区域颜色
                TextEditor.TextArea.SelectionBrush = new SolidColorBrush(theme.PrimaryMid.Color) { Opacity = 0.3 };
                TextEditor.TextArea.SelectionBorder = new Pen(new SolidColorBrush(theme.PrimaryMid.Color), 1);

                // 设置光标颜色
                TextEditor.TextArea.Caret.CaretBrush = new SolidColorBrush(theme.Body);

                // 更新查找面板的主题
                UpdateSearchPanelTheme(theme);
            }
            catch (Exception ex)
            {
                // 如果主题应用失败，使用默认颜色
                System.Diagnostics.Debug.WriteLine($"应用编辑器主题失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新查找面板的主题
        /// </summary>
        private void UpdateSearchPanelTheme(ITheme theme)
        {
            try
            {
                // 查找面板
                if (FindPanel != null)
                {
                    FindPanel.Background = new SolidColorBrush(theme.CardBackground);
                    FindPanel.Foreground = new SolidColorBrush(theme.Body);
                }

                if (FindTextBox != null)
                {
                    FindTextBox.Background = new SolidColorBrush(theme.Background);
                    FindTextBox.Foreground = new SolidColorBrush(theme.Body);
                    FindTextBox.BorderBrush = new SolidColorBrush(theme.PrimaryMid.Color);
                }

                // 替换面板
                if (ReplacePanel != null)
                {
                    ReplacePanel.Background = new SolidColorBrush(theme.CardBackground);
                    ReplacePanel.Foreground = new SolidColorBrush(theme.Body);
                }

                if (ReplaceFindTextBox != null)
                {
                    ReplaceFindTextBox.Background = new SolidColorBrush(theme.Background);
                    ReplaceFindTextBox.Foreground = new SolidColorBrush(theme.Body);
                    ReplaceFindTextBox.BorderBrush = new SolidColorBrush(theme.PrimaryMid.Color);
                }

                if (ReplaceTextBox != null)
                {
                    ReplaceTextBox.Background = new SolidColorBrush(theme.Background);
                    ReplaceTextBox.Foreground = new SolidColorBrush(theme.Body);
                    ReplaceTextBox.BorderBrush = new SolidColorBrush(theme.PrimaryMid.Color);
                }

                // 删除面板
                if (DeletePanel != null)
                {
                    DeletePanel.Background = new SolidColorBrush(theme.CardBackground);
                    DeletePanel.Foreground = new SolidColorBrush(theme.Body);
                }

                if (DeleteTextBox != null)
                {
                    DeleteTextBox.Background = new SolidColorBrush(theme.Background);
                    DeleteTextBox.Foreground = new SolidColorBrush(theme.Body);
                    DeleteTextBox.BorderBrush = new SolidColorBrush(theme.PrimaryMid.Color);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新查找面板主题失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 响应主题变更
        /// </summary>
        public void OnThemeChanged()
        {
            ApplyCurrentTheme();
        }

        private void DocumentEditor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.S && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                Save_Click(sender, e);
                e.Handled = true;
            }
        }

        private void UpdateTitle()
        {
            // 这里可以更新窗口标题或其他UI元素
            // 由于这是UserControl，标题更新可能需要通过事件通知父窗口
        }

        /// <summary>
        /// 初始化状态更新定时器
        /// </summary>
        private void InitializeStatusTimer()
        {
            _statusUpdateTimer = new System.Windows.Threading.DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(2) // 每2秒更新一次
            };
            _statusUpdateTimer.Tick += StatusUpdateTimer_Tick;
            _statusUpdateTimer.Start();
        }

        /// <summary>
        /// 状态更新定时器事件
        /// </summary>
        private void StatusUpdateTimer_Tick(object? sender, EventArgs e)
        {
            try
            {
                UpdateSystemMonitorInfo();
                // AI模型信息现在由主窗口底部状态栏显示，不再在文档编辑器中显示
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"状态更新失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新系统监控信息
        /// </summary>
        private async void UpdateSystemMonitorInfo()
        {
            if (_systemMonitorService == null) return;

            try
            {
                var resourceInfo = await _systemMonitorService.GetSystemResourceInfoAsync();

                if (CpuUsageText != null)
                    CpuUsageText.Text = $"{resourceInfo.Cpu.UsagePercentage:F1}%";

                if (MemoryUsageText != null)
                    MemoryUsageText.Text = $"{resourceInfo.Memory.UsagePercentage:F1}%";

                if (GpuUsageText != null)
                    GpuUsageText.Text = $"{resourceInfo.Gpu.UsagePercentage:F1}%";

                if (GpuMemoryText != null)
                {
                    var memoryUsagePercent = resourceInfo.Gpu.TotalMemoryMB > 0
                        ? (double)resourceInfo.Gpu.UsedMemoryMB / resourceInfo.Gpu.TotalMemoryMB * 100
                        : 0;
                    GpuMemoryText.Text = $"{memoryUsagePercent:F1}%";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新系统监控信息失败: {ex.Message}");
            }
        }



        /// <summary>
        /// 显示AI处理状态
        /// </summary>
        public void ShowAIProcessingStatus(string status)
        {
            if (AIProcessingIndicator != null && AIProcessingText != null)
            {
                AIProcessingIndicator.Visibility = Visibility.Visible;
                AIProcessingText.Text = status;
            }
        }

        /// <summary>
        /// 隐藏AI处理状态
        /// </summary>
        public void HideAIProcessingStatus()
        {
            if (AIProcessingIndicator != null)
            {
                AIProcessingIndicator.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 更新文档状态
        /// </summary>
        public void UpdateDocumentStatus(string status, string? filePath = null)
        {
            if (DocumentStatusText != null)
                DocumentStatusText.Text = status;

            if (CurrentFileText != null && !string.IsNullOrEmpty(filePath))
                CurrentFileText.Text = Path.GetFileName(filePath);
        }

        private void UpdateWordCount()
        {
            if (TextEditor == null) return;

            var text = TextEditor.Text;
            var stats = CalculateDetailedStats(text);

            if (WordCountDisplay != null)
            {
                WordCountDisplay.Text = $"字数: {stats.TotalWords} | 字符: {stats.TotalChars} | 行数: {stats.Lines}";
            }

            // 更新详细统计信息
            UpdateDetailedStatsDisplay(stats);
        }

        private DocumentStats CalculateDetailedStats(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return new DocumentStats();
            }

            var stats = new DocumentStats();

            // 基本计数
            stats.TotalChars = text.Length;
            stats.CharsNoSpace = text.Count(c => !char.IsWhiteSpace(c));
            stats.Lines = TextEditor?.LineCount ?? text.Split('\n').Length;

            // 中文字符计数
            stats.ChineseChars = Regex.Matches(text, @"[\u4e00-\u9fa5]").Count;

            // 英文单词计数
            stats.EnglishWords = Regex.Matches(text, @"\b[a-zA-Z]+\b").Count;

            // 总字数（中文字符 + 英文单词）
            stats.TotalWords = stats.ChineseChars + stats.EnglishWords;

            // 段落计数（以双换行符分隔）
            stats.Paragraphs = text.Split(new[] { "\r\n\r\n", "\n\n" }, StringSplitOptions.RemoveEmptyEntries).Length;

            // 句子计数（以句号、问号、感叹号结尾）
            stats.Sentences = Regex.Matches(text, @"[。！？.!?]+").Count;

            // 预计阅读时间（中文300字/分钟，英文200词/分钟）
            var chineseReadingTime = stats.ChineseChars / 300.0;
            var englishReadingTime = stats.EnglishWords / 200.0;
            stats.EstimatedReadingMinutes = Math.Max(1, (int)Math.Ceiling(chineseReadingTime + englishReadingTime));

            return stats;
        }

        private void UpdateDetailedStatsDisplay(DocumentStats stats)
        {
            if (TotalWordsText != null) TotalWordsText.Text = stats.TotalWords.ToString();
            if (ChineseCharsText != null) ChineseCharsText.Text = stats.ChineseChars.ToString();
            if (EnglishWordsText != null) EnglishWordsText.Text = stats.EnglishWords.ToString();
            if (TotalCharsText != null) TotalCharsText.Text = stats.TotalChars.ToString();
            if (CharsNoSpaceText != null) CharsNoSpaceText.Text = stats.CharsNoSpace.ToString();
            if (ParagraphsText != null) ParagraphsText.Text = stats.Paragraphs.ToString();
            if (LinesText != null) LinesText.Text = stats.Lines.ToString();
            if (SentencesText != null) SentencesText.Text = stats.Sentences.ToString();
            if (ReadingTimeText != null) ReadingTimeText.Text = $"{stats.EstimatedReadingMinutes}分钟";
        }

        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            // 中文字符计数
            var chineseCharCount = Regex.Matches(text, @"[\u4e00-\u9fa5]").Count;

            // 英文单词计数
            var englishWords = Regex.Matches(text, @"\b[a-zA-Z]+\b").Count;

            return chineseCharCount + englishWords;
        }

        // 格式化按钮事件
        private void Bold_Click(object sender, RoutedEventArgs e)
        {
            // 这里可以实现粗体格式化
            // 由于AvalonEdit主要用于代码编辑，富文本格式化需要额外实现
            InsertFormatting("**", "**"); // Markdown格式
        }

        private void Italic_Click(object sender, RoutedEventArgs e)
        {
            InsertFormatting("*", "*"); // Markdown格式
        }

        private void Underline_Click(object sender, RoutedEventArgs e)
        {
            InsertFormatting("<u>", "</u>"); // HTML格式
        }

        private void InsertFormatting(string startTag, string endTag)
        {
            if (TextEditor == null) return;

            var selectedText = TextEditor.SelectedText;
            var selectionStart = TextEditor.SelectionStart;
            var selectionLength = TextEditor.SelectionLength;

            if (!string.IsNullOrEmpty(selectedText))
            {
                var formattedText = startTag + selectedText + endTag;
                TextEditor.SelectedText = formattedText;
                TextEditor.Select(selectionStart + startTag.Length, selectedText.Length);
            }
            else
            {
                var insertText = startTag + endTag;
                TextEditor.Document.Insert(TextEditor.CaretOffset, insertText);
                TextEditor.CaretOffset = TextEditor.CaretOffset - endTag.Length;
            }
        }

        private void FontSize_Changed(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (TextEditor != null && FontSizeComboBox.SelectedItem is ComboBoxItem item &&
                double.TryParse(item.Content.ToString(), out double fontSize))
            {
                TextEditor.FontSize = fontSize;
            }
        }

        private void Undo_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor?.CanUndo == true)
                TextEditor.Undo();
        }

        private void Redo_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor?.CanRedo == true)
                TextEditor.Redo();
        }

        private void Find_Click(object sender, RoutedEventArgs e)
        {
            // 隐藏其他面板
            ReplacePanel.Visibility = Visibility.Collapsed;
            DeletePanel.Visibility = Visibility.Collapsed;

            FindPanel.Visibility = Visibility.Visible;
            FindTextBox.Focus();
        }

        private void Replace_Click(object sender, RoutedEventArgs e)
        {
            // 隐藏其他面板
            FindPanel.Visibility = Visibility.Collapsed;
            DeletePanel.Visibility = Visibility.Collapsed;

            ReplacePanel.Visibility = Visibility.Visible;
            ReplaceFindTextBox.Focus();
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            // 隐藏其他面板
            FindPanel.Visibility = Visibility.Collapsed;
            ReplacePanel.Visibility = Visibility.Collapsed;

            DeletePanel.Visibility = Visibility.Visible;
            DeleteTextBox.Focus();
        }

        private void FindTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                FindNext_Click(sender, e);
            }
            else if (e.Key == Key.Escape)
            {
                CloseFindPanel_Click(sender, e);
            }
        }

        private void FindNext_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var searchText = FindTextBox.Text;
            if (string.IsNullOrEmpty(searchText))
                return;

            var text = TextEditor.Text;
            var startIndex = Math.Max(0, TextEditor.CaretOffset);
            var index = text.IndexOf(searchText, startIndex, StringComparison.OrdinalIgnoreCase);

            if (index == -1 && startIndex > 0)
            {
                // 从头开始搜索
                index = text.IndexOf(searchText, 0, StringComparison.OrdinalIgnoreCase);
            }

            if (index != -1)
            {
                TextEditor.Select(index, searchText.Length);
                TextEditor.ScrollToLine(TextEditor.Document.GetLineByOffset(index).LineNumber);
                _lastFindIndex = index;
            }
            else
            {
                System.Windows.MessageBox.Show("未找到指定内容", "查找结果",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void FindPrevious_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var searchText = FindTextBox.Text;
            if (string.IsNullOrEmpty(searchText))
                return;

            var text = TextEditor.Text;
            var startIndex = Math.Max(0, TextEditor.CaretOffset - 1);
            var index = text.LastIndexOf(searchText, startIndex, StringComparison.OrdinalIgnoreCase);

            if (index == -1 && startIndex < text.Length - 1)
            {
                // 从末尾开始搜索
                index = text.LastIndexOf(searchText, StringComparison.OrdinalIgnoreCase);
            }

            if (index != -1)
            {
                TextEditor.Select(index, searchText.Length);
                TextEditor.ScrollToLine(TextEditor.Document.GetLineByOffset(index).LineNumber);
                _lastFindIndex = index;
            }
            else
            {
                System.Windows.MessageBox.Show("未找到指定内容", "查找结果",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void CloseFindPanel_Click(object sender, RoutedEventArgs e)
        {
            if (FindPanel != null)
                FindPanel.Visibility = Visibility.Collapsed;
            TextEditor?.Focus();
        }

        // 替换面板事件处理
        private void ReplaceFindTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ReplaceFindNext_Click(sender, e);
            }
            else if (e.Key == Key.Escape)
            {
                CloseReplacePanel_Click(sender, e);
            }
        }

        private void ReplaceTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ReplaceOne_Click(sender, e);
            }
            else if (e.Key == Key.Escape)
            {
                CloseReplacePanel_Click(sender, e);
            }
        }

        private void ReplaceFindNext_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var searchText = ReplaceFindTextBox.Text;
            if (string.IsNullOrEmpty(searchText))
                return;

            var text = TextEditor.Text;
            var startIndex = Math.Max(0, TextEditor.CaretOffset);
            var index = text.IndexOf(searchText, startIndex, StringComparison.OrdinalIgnoreCase);

            if (index == -1 && startIndex > 0)
            {
                // 从头开始搜索
                index = text.IndexOf(searchText, 0, StringComparison.OrdinalIgnoreCase);
            }

            if (index != -1)
            {
                TextEditor.Select(index, searchText.Length);
                TextEditor.ScrollToLine(TextEditor.Document.GetLineByOffset(index).LineNumber);
                _lastFindIndex = index;
            }
            else
            {
                System.Windows.MessageBox.Show("未找到指定内容", "查找结果",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void ReplaceFindPrevious_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var searchText = ReplaceFindTextBox.Text;
            if (string.IsNullOrEmpty(searchText))
                return;

            var text = TextEditor.Text;
            var startIndex = Math.Max(0, TextEditor.CaretOffset - 1);
            var index = text.LastIndexOf(searchText, startIndex, StringComparison.OrdinalIgnoreCase);

            if (index == -1 && startIndex < text.Length - 1)
            {
                // 从末尾开始搜索
                index = text.LastIndexOf(searchText, StringComparison.OrdinalIgnoreCase);
            }

            if (index != -1)
            {
                TextEditor.Select(index, searchText.Length);
                TextEditor.ScrollToLine(TextEditor.Document.GetLineByOffset(index).LineNumber);
                _lastFindIndex = index;
            }
            else
            {
                System.Windows.MessageBox.Show("未找到指定内容", "查找结果",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void ReplaceOne_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var searchText = ReplaceFindTextBox.Text;
            var replaceText = ReplaceTextBox.Text ?? "";

            if (string.IsNullOrEmpty(searchText))
            {
                System.Windows.MessageBox.Show("请输入要查找的内容", "提示",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 如果当前有选中文本且与查找文本匹配，则替换
            if (TextEditor.SelectionLength > 0 &&
                string.Equals(TextEditor.SelectedText, searchText, StringComparison.OrdinalIgnoreCase))
            {
                TextEditor.SelectedText = replaceText;
                SetModified(true);

                // 查找下一个
                ReplaceFindNext_Click(sender, e);
            }
            else
            {
                // 查找第一个匹配项
                ReplaceFindNext_Click(sender, e);
            }
        }

        private void ReplaceAll_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var searchText = ReplaceFindTextBox.Text;
            var replaceText = ReplaceTextBox.Text ?? "";

            if (string.IsNullOrEmpty(searchText))
            {
                System.Windows.MessageBox.Show("请输入要查找的内容", "提示",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var text = TextEditor.Text;
            var count = 0;
            var index = 0;

            // 计算替换次数
            while ((index = text.IndexOf(searchText, index, StringComparison.OrdinalIgnoreCase)) != -1)
            {
                count++;
                index += searchText.Length;
            }

            if (count == 0)
            {
                System.Windows.MessageBox.Show("未找到要替换的内容", "替换结果",
                    MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var result = System.Windows.MessageBox.Show(
                $"找到 {count} 个匹配项，确定要全部替换吗？",
                "确认替换",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                // 执行替换
                var newText = text.Replace(searchText, replaceText);
                TextEditor.Text = newText;
                SetModified(true);

                System.Windows.MessageBox.Show($"已成功替换 {count} 个匹配项", "替换完成",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void CloseReplacePanel_Click(object sender, RoutedEventArgs e)
        {
            if (ReplacePanel != null)
                ReplacePanel.Visibility = Visibility.Collapsed;
            TextEditor?.Focus();
        }

        // 删除面板事件处理
        private void DeleteTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DeleteAll_Click(sender, e);
            }
            else if (e.Key == Key.Escape)
            {
                CloseDeletePanel_Click(sender, e);
            }
        }

        private void DeleteAll_Click(object sender, RoutedEventArgs e)
        {
            if (TextEditor == null) return;

            var deleteText = DeleteTextBox.Text;

            if (string.IsNullOrEmpty(deleteText))
            {
                System.Windows.MessageBox.Show("请输入要删除的字符串", "提示",
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var text = TextEditor.Text;
            var count = 0;
            var index = 0;

            // 计算删除次数
            while ((index = text.IndexOf(deleteText, index, StringComparison.OrdinalIgnoreCase)) != -1)
            {
                count++;
                index += deleteText.Length;
            }

            if (count == 0)
            {
                System.Windows.MessageBox.Show("未找到要删除的字符串", "删除结果",
                    MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var result = System.Windows.MessageBox.Show(
                $"找到 {count} 个匹配的字符串，确定要全部删除吗？",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                // 执行删除（替换为空字符串）
                var newText = text.Replace(deleteText, "");
                TextEditor.Text = newText;
                SetModified(true);

                System.Windows.MessageBox.Show($"已成功删除 {count} 个匹配的字符串", "删除完成",
                    MessageBoxButton.OK, MessageBoxImage.Information);

                // 关闭删除面板
                CloseDeletePanel_Click(sender, e);
            }
        }

        private void CloseDeletePanel_Click(object sender, RoutedEventArgs e)
        {
            if (DeletePanel != null)
                DeletePanel.Visibility = Visibility.Collapsed;
            TextEditor?.Focus();
        }

        public void InsertText(string text)
        {
            if (TextEditor != null)
                TextEditor.Document.Insert(TextEditor.CaretOffset, text);
        }

        public void ReplaceSelectedText(string text)
        {
            if (HasSelection)
            {
                if (TextEditor != null)
                    TextEditor.SelectedText = text;
            }
            else
            {
                InsertText(text);
            }
        }

        public void SelectAll()
        {
            TextEditor?.SelectAll();
        }

        public void Copy()
        {
            TextEditor?.Copy();
        }

        public void Cut()
        {
            TextEditor?.Cut();
        }

        public void Paste()
        {
            TextEditor?.Paste();
        }

        // 右键菜单事件处理 - 基础编辑功能
        private void ContextMenu_Copy_Click(object sender, RoutedEventArgs e)
        {
            Copy();
        }

        private void ContextMenu_Cut_Click(object sender, RoutedEventArgs e)
        {
            Cut();
        }

        private void ContextMenu_Paste_Click(object sender, RoutedEventArgs e)
        {
            Paste();
        }

        private void ContextMenu_SelectAll_Click(object sender, RoutedEventArgs e)
        {
            SelectAll();
        }

        // 右键菜单事件处理 - AI功能
        private async void ContextMenu_ExpandText_Click(object sender, RoutedEventArgs e)
        {
            await HandleExpandTextAsync();
        }

        private async void ContextMenu_PolishText_Click(object sender, RoutedEventArgs e)
        {
            await HandlePolishTextAsync();
        }

        private async void ContextMenu_TranslateText_Click(object sender, RoutedEventArgs e)
        {
            await HandleTranslateTextAsync();
        }

        private async void ContextMenu_ContinueWriting_Click(object sender, RoutedEventArgs e)
        {
            await HandleContinueWritingAsync();
        }

        private async void ContextMenu_SummarizeText_Click(object sender, RoutedEventArgs e)
        {
            await HandleSummarizeTextAsync();
        }

        // AI功能处理方法
        private async Task HandleExpandTextAsync()
        {
            try
            {
                var selectedText = SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    System.Windows.MessageBox.Show("请先选择要扩写的文本内容。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 显示扩写要求输入对话框
                var expandDialog = new Views.Dialogs.ExpandTextDialog();
                if (expandDialog.ShowDialog() != true)
                    return;

                ShowAIProcessingStatus("正在扩写内容...");

                if (_aiService != null)
                {
                    var expandedText = await _aiService.ExpandTextAsync(
                        selectedText,
                        expandDialog.TargetLength,
                        expandDialog.Requirements);

                    ShowExpandPreview(selectedText, expandedText, true);
                    UpdateDocumentStatus("内容扩写完成");
                }
                else
                {
                    System.Windows.MessageBox.Show("AI服务未初始化，请检查AI配置。", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"扩写文本时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                HideAIProcessingStatus();
            }
        }

        private async Task HandlePolishTextAsync()
        {
            try
            {
                var selectedText = SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    System.Windows.MessageBox.Show("请先选择要润色的文本内容。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 显示润色风格选择对话框
                var polishDialog = new Views.Dialogs.PolishTextDialog();
                if (polishDialog.ShowDialog() != true)
                    return;

                ShowAIProcessingStatus("正在润色内容...");

                if (_aiService != null)
                {
                    var polishedText = await _aiService.PolishTextAsync(selectedText, polishDialog.SelectedStyle);
                    ShowPolishPreview(selectedText, polishedText, true);
                    UpdateDocumentStatus("内容润色完成");
                }
                else
                {
                    System.Windows.MessageBox.Show("AI服务未初始化，请检查AI配置。", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"润色文本时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                HideAIProcessingStatus();
            }
        }

        private async Task HandleTranslateTextAsync()
        {
            try
            {
                var selectedText = SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    System.Windows.MessageBox.Show("请先选择要翻译的文本内容。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 显示翻译语言选择对话框
                var translateDialog = new Views.Dialogs.TranslateTextDialog();
                if (translateDialog.ShowDialog() != true)
                    return;

                ShowAIProcessingStatus("正在翻译内容...");

                if (_aiService != null)
                {
                    var translatedText = await _aiService.TranslateTextAsync(
                        selectedText,
                        translateDialog.SourceLanguage,
                        translateDialog.TargetLanguage);

                    ShowTranslatePreview(selectedText, translatedText, true);
                    UpdateDocumentStatus("内容翻译完成");
                }
                else
                {
                    System.Windows.MessageBox.Show("AI服务未初始化，请检查AI配置。", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"翻译文本时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                HideAIProcessingStatus();
            }
        }

        private async Task HandleContinueWritingAsync()
        {
            try
            {
                var currentText = Text;
                if (string.IsNullOrWhiteSpace(currentText))
                {
                    System.Windows.MessageBox.Show("文档内容为空，无法进行续写。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 获取光标位置前的文本作为上下文
                var caretOffset = TextEditor?.CaretOffset ?? 0;
                var contextText = currentText.Substring(0, Math.Min(caretOffset, currentText.Length));

                // 取最后1000字符作为上下文
                if (contextText.Length > 1000)
                {
                    contextText = contextText.Substring(contextText.Length - 1000);
                }

                ShowAIProcessingStatus("正在智能续写...");

                if (_aiService != null)
                {
                    var continuedText = await _aiService.ContinueWritingAsync(contextText, 500);

                    // 在光标位置插入续写内容
                    if (TextEditor != null)
                    {
                        TextEditor.Document.Insert(caretOffset, "\n" + continuedText);
                        SetModified(true);
                    }

                    UpdateDocumentStatus("智能续写完成");
                }
                else
                {
                    System.Windows.MessageBox.Show("AI服务未初始化，请检查AI配置。", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"续写文本时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                HideAIProcessingStatus();
            }
        }

        private async Task HandleSummarizeTextAsync()
        {
            try
            {
                var selectedText = SelectedText;
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    System.Windows.MessageBox.Show("请先选择要总结的文本内容。", "提示",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                ShowAIProcessingStatus("正在生成内容总结...");

                if (_aiService != null)
                {
                    var summary = await _aiService.SummarizeTextAsync(selectedText);

                    // 显示总结结果对话框
                    var summaryDialog = new Views.Dialogs.SummaryResultDialog(selectedText, summary);
                    if (summaryDialog.ShowDialog() == true && summaryDialog.ShouldInsertToDocument)
                    {
                        // 在光标位置插入总结内容
                        if (TextEditor != null)
                        {
                            var insertText = $"\n\n【内容总结】\n{summary}\n";
                            TextEditor.Document.Insert(TextEditor.CaretOffset, insertText);
                            SetModified(true);
                        }
                    }

                    UpdateDocumentStatus("内容总结完成");
                }
                else
                {
                    System.Windows.MessageBox.Show("AI服务未初始化，请检查AI配置。", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"总结文本时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                HideAIProcessingStatus();
            }
        }



        // 详细统计按钮点击事件
        private void DetailedStats_Click(object sender, RoutedEventArgs e)
        {
            if (StatsPopup != null)
            {
                StatsPopup.IsOpen = !StatsPopup.IsOpen;
            }
        }

        // 关闭统计弹窗
        private void CloseStatsPopup_Click(object sender, RoutedEventArgs e)
        {
            if (StatsPopup != null)
            {
                StatsPopup.IsOpen = false;
            }
        }

        // 保存按钮点击事件
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(_currentFilePath))
            {
                SaveAs_Click(sender, e);
                return;
            }

            try
            {
                await SaveDocumentAsync(_currentFilePath);
                IsModified = false;
                MessageBox.Show("文档保存成功！", "保存", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存文档时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 章节重写按钮点击事件
        private async void RewriteChapter_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (TextEditor == null) return;

                // 检查当前是否有打开的文件
                if (string.IsNullOrEmpty(_currentFilePath))
                {
                    MessageBox.Show("请先打开一个章节文件", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 检查文件名是否符合章节格式
                var fileName = Path.GetFileNameWithoutExtension(_currentFilePath);
                if (!IsChapterFile(fileName))
                {
                    MessageBox.Show("当前文件不是章节文件，无法进行章节重写", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 提取章节号
                var chapterNumber = ExtractChapterNumber(fileName);
                if (chapterNumber <= 0)
                {
                    MessageBox.Show("无法识别章节号，请确保文件名包含章节信息", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 检查是否有未完成的重写任务
                var chapterRewriteService = GetChapterRewriteService();
                if (chapterRewriteService != null)
                {
                    var incompleteTask = await chapterRewriteService.LoadConfigAsync(chapterNumber);
                    if (incompleteTask != null && incompleteTask.Status == Models.ChapterRewriteStatus.InProgress)
                    {
                        var resumeResult = MessageBox.Show(
                            $"检测到第{chapterNumber}章有未完成的重写任务（进度：{incompleteTask.Progress}%）。\n\n是否继续之前的任务？\n\n点击\"是\"继续之前的任务\n点击\"否\"开始新的重写任务\n点击\"取消\"退出",
                            "发现未完成任务",
                            MessageBoxButton.YesNoCancel,
                            MessageBoxImage.Question);

                        if (resumeResult == MessageBoxResult.Cancel)
                            return;

                        if (resumeResult == MessageBoxResult.Yes)
                        {
                            // 续写之前的任务
                            await ResumeChapterRewrite(incompleteTask);
                            return;
                        }
                    }
                }

                // 显示关联文件选择对话框
                var selectionDialog = new Views.RelatedFilesSelectionDialog(_currentProjectPath ?? "", chapterNumber);
                if (selectionDialog.ShowDialog() != true)
                    return;

                // 创建重写配置
                var config = new Models.ChapterRewriteConfig
                {
                    ChapterNumber = chapterNumber,
                    ChapterFilePath = _currentFilePath,
                    ProjectPath = _currentProjectPath ?? "",
                    ReferenceFilePaths = selectionDialog.SelectedFilePaths,
                    AutoSave = selectionDialog.AutoSave,
                    BackupOriginal = selectionDialog.BackupOriginal,
                    EnableResume = selectionDialog.EnableResume,
                    MaxContextLength = selectionDialog.MaxContextLength,
                    RewriteStyle = selectionDialog.RewriteStyle
                };

                ShowAIProcessingStatus("正在重写章节...");

                // 触发增强的章节重写事件
                EnhancedChapterRewriteRequested?.Invoke(this, new Models.EnhancedChapterRewriteEventArgs
                {
                    Config = config,
                    IsResume = false
                });
            }
            catch (Exception ex)
            {
                HideAIProcessingStatus();
                MessageBox.Show($"章节重写时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 检查文件是否为章节文件
        /// </summary>
        private bool IsChapterFile(string fileName)
        {
            // 检查文件名是否包含章节标识
            return fileName.Contains("章") || fileName.Contains("Chapter") ||
                   fileName.Contains("_章") || fileName.Contains("_第") ||
                   System.Text.RegularExpressions.Regex.IsMatch(fileName, @"第\d+章") ||
                   System.Text.RegularExpressions.Regex.IsMatch(fileName, @"章\d+");
        }

        /// <summary>
        /// 从文件名中提取章节号
        /// </summary>
        private int ExtractChapterNumber(string fileName)
        {
            // 尝试多种模式匹配章节号
            var patterns = new[]
            {
                @"第(\d+)章",
                @"章(\d+)",
                @"Chapter(\d+)",
                @"_章(\d+)_",
                @"_第(\d+)章_",
                @"章节(\d+)"
            };

            foreach (var pattern in patterns)
            {
                var match = System.Text.RegularExpressions.Regex.Match(fileName, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (match.Success && int.TryParse(match.Groups[1].Value, out var chapterNumber))
                {
                    return chapterNumber;
                }
            }

            return 0;
        }

        /// <summary>
        /// 获取章节重写服务
        /// </summary>
        private Services.ChapterRewriteService? GetChapterRewriteService()
        {
            // 这里应该从依赖注入容器获取服务
            // 暂时返回null，在主窗口中处理
            return null;
        }

        /// <summary>
        /// 续写章节重写任务
        /// </summary>
        private async Task ResumeChapterRewrite(Models.ChapterRewriteConfig config)
        {
            try
            {
                ShowAIProcessingStatus($"正在续写第{config.ChapterNumber}章...");

                // 触发续写事件
                EnhancedChapterRewriteRequested?.Invoke(this, new Models.EnhancedChapterRewriteEventArgs
                {
                    Config = config,
                    IsResume = true
                });
            }
            catch (Exception ex)
            {
                HideAIProcessingStatus();
                MessageBox.Show($"续写章节时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 另存为按钮点击事件
        private async void SaveAs_Click(object sender, RoutedEventArgs e)
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Word文档 (*.docx)|*.docx|文本文件 (*.txt)|*.txt|Markdown文件 (*.md)|*.md",
                DefaultExt = "docx",
                InitialDirectory = _currentProjectPath ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    await SaveDocumentAsync(saveFileDialog.FileName);
                    CurrentFilePath = saveFileDialog.FileName;
                    IsModified = false;
                    MessageBox.Show("文档保存成功！", "保存", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存文档时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 保存文档到指定路径
        /// </summary>
        public async Task SaveDocumentAsync(string filePath)
        {
            if (TextEditor == null) return;

            var extension = Path.GetExtension(filePath).ToLower();
            var content = TextEditor.Text;

            switch (extension)
            {
                case ".docx":
                    await SaveAsWordDocumentAsync(filePath, content);
                    break;
                case ".txt":
                    await File.WriteAllTextAsync(filePath, content);
                    break;
                case ".md":
                    await File.WriteAllTextAsync(filePath, content);
                    break;
                default:
                    throw new NotSupportedException($"不支持的文件格式：{extension}");
            }

            // 触发文档保存事件
            DocumentSaved?.Invoke(this, new DocumentSavedEventArgs(filePath, content));

            // 如果设置了向量服务，进行文档向量化
            if (_vectorService != null && !string.IsNullOrEmpty(_currentProjectPath))
            {
                try
                {
                    await VectorizeDocumentAsync(filePath, content);
                }
                catch (Exception ex)
                {
                    // 向量化失败不影响保存，只记录错误
                    System.Diagnostics.Debug.WriteLine($"文档向量化失败：{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 保存为Word文档
        /// </summary>
        private async Task SaveAsWordDocumentAsync(string filePath, string content)
        {
            await Task.Run(() =>
            {
                using var wordDocument = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);
                var mainPart = wordDocument.AddMainDocumentPart();
                mainPart.Document = new Document();
                var body = mainPart.Document.AppendChild(new Body());

                // 将文本按段落分割
                var paragraphs = content.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);

                foreach (var paragraphText in paragraphs)
                {
                    var paragraph = new Paragraph();
                    var run = new Run();
                    var text = new Text(paragraphText);

                    run.Append(text);
                    paragraph.Append(run);
                    body.Append(paragraph);
                }
            });
        }

        /// <summary>
        /// 对文档进行向量化
        /// </summary>
        private async Task VectorizeDocumentAsync(string filePath, string content)
        {
            if (_vectorService == null || string.IsNullOrEmpty(content))
                return;

            try
            {
                // 将文档分块进行向量化
                var chunks = SplitTextIntoChunks(content, 500); // 每块500字符

                for (int i = 0; i < chunks.Count; i++)
                {
                    var chunk = chunks[i];
                    if (string.IsNullOrWhiteSpace(chunk))
                        continue;

                    // 生成向量ID
                    var vectorId = $"{Path.GetFileNameWithoutExtension(filePath)}_{i}_{Guid.NewGuid():N}";

                    // 调用向量服务进行向量化
                    await _vectorService.AddDocumentAsync(vectorId, chunk, new Dictionary<string, object>
                    {
                        ["file_path"] = filePath,
                        ["chunk_index"] = i,
                        ["total_chunks"] = chunks.Count,
                        ["created_at"] = DateTime.UtcNow.ToString("O")
                    });
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"文档向量化失败：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 将文本分割成块
        /// </summary>
        private List<string> SplitTextIntoChunks(string text, int maxChunkSize)
        {
            var chunks = new List<string>();

            if (string.IsNullOrEmpty(text))
                return chunks;

            // 按段落分割
            var paragraphs = text.Split(new[] { "\r\n\r\n", "\n\n" }, StringSplitOptions.RemoveEmptyEntries);

            var currentChunk = "";

            foreach (var paragraph in paragraphs)
            {
                if (currentChunk.Length + paragraph.Length <= maxChunkSize)
                {
                    if (!string.IsNullOrEmpty(currentChunk))
                        currentChunk += "\n\n";
                    currentChunk += paragraph;
                }
                else
                {
                    if (!string.IsNullOrEmpty(currentChunk))
                    {
                        chunks.Add(currentChunk);
                        currentChunk = "";
                    }

                    // 如果单个段落太长，需要进一步分割
                    if (paragraph.Length > maxChunkSize)
                    {
                        var sentences = paragraph.Split(new[] { '。', '！', '？', '.', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
                        var sentenceChunk = "";

                        foreach (var sentence in sentences)
                        {
                            if (sentenceChunk.Length + sentence.Length <= maxChunkSize)
                            {
                                sentenceChunk += sentence + "。";
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(sentenceChunk))
                                {
                                    chunks.Add(sentenceChunk);
                                    sentenceChunk = "";
                                }
                                sentenceChunk = sentence + "。";
                            }
                        }

                        if (!string.IsNullOrEmpty(sentenceChunk))
                        {
                            chunks.Add(sentenceChunk);
                        }
                    }
                    else
                    {
                        currentChunk = paragraph;
                    }
                }
            }

            if (!string.IsNullOrEmpty(currentChunk))
            {
                chunks.Add(currentChunk);
            }

            return chunks;
        }

        /// <summary>
        /// 加载文档
        /// </summary>
        public async Task LoadDocumentAsync(string filePath)
        {
            try
            {
                var extension = Path.GetExtension(filePath).ToLower();
                string content;

                switch (extension)
                {
                    case ".docx":
                        content = await LoadWordDocumentAsync(filePath);
                        break;
                    case ".txt":
                    case ".md":
                        content = await File.ReadAllTextAsync(filePath);
                        break;
                    default:
                        throw new NotSupportedException($"不支持的文件格式：{extension}");
                }

                if (TextEditor != null)
                {
                    TextEditor.Text = content;
                }
                CurrentFilePath = filePath;
                IsModified = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文档时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载Word文档
        /// </summary>
        private async Task<string> LoadWordDocumentAsync(string filePath)
        {
            return await Task.Run(() =>
            {
                using var wordDocument = WordprocessingDocument.Open(filePath, false);
                var body = wordDocument.MainDocumentPart?.Document?.Body;

                if (body == null)
                    return string.Empty;

                var text = "";
                foreach (var paragraph in body.Elements<Paragraph>())
                {
                    text += paragraph.InnerText + "\n";
                }

                return text;
            });
        }

        #region AI输出预览功能

        /// <summary>
        /// 显示AI输出预览（简化版本，使用消息框显示）
        /// </summary>
        /// <param name="content">预览内容</param>
        /// <param name="title">内容标题</param>
        public void ShowPreview(string content, string title = "")
        {
            try
            {
                // 简化版本：直接使用消息框显示内容，并提供选项
                var result = MessageBox.Show(
                    $"{title}\n\n{content}\n\n是否要将此内容添加到编辑器中？",
                    "AI输出预览",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Information);

                if (result == MessageBoxResult.Yes)
                {
                    // 直接使用Text属性添加内容（简化方法）
                    this.Text += "\n\n" + content;
                }

                System.Diagnostics.Debug.WriteLine($"AI输出预览已显示，内容长度: {content?.Length ?? 0}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"显示预览时发生错误: {ex.Message}");
                // 如果出错，至少显示内容
                MessageBox.Show($"{title}\n\n{content}", "AI输出预览", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        #endregion

        public class TextChangedEventArgs : EventArgs
        {
        }

        public class SelectionChangedEventArgs : EventArgs
        {
        }

        public class DocumentSavedEventArgs : EventArgs
        {
            public string FilePath { get; }
            public string Content { get; }

            public DocumentSavedEventArgs(string filePath, string content)
            {
                FilePath = filePath;
                Content = content;
            }
        }

        /// <summary>
        /// 文档统计信息
        /// </summary>
        public class DocumentStats
        {
            public int TotalWords { get; set; }
            public int ChineseChars { get; set; }
            public int EnglishWords { get; set; }
            public int TotalChars { get; set; }
            public int CharsNoSpace { get; set; }
            public int Paragraphs { get; set; }
            public int Lines { get; set; }
            public int Sentences { get; set; }
            public int EstimatedReadingMinutes { get; set; }
        }

    #region 润色预览功能

    /// <summary>
    /// 显示润色预览
    /// </summary>
    /// <param name="originalText">原文</param>
    /// <param name="polishedText">润色后文本</param>
    /// <param name="useFloatingControl">是否使用悬浮控件</param>
    public void ShowPolishPreview(string originalText, string polishedText, bool useFloatingControl = false)
    {
        if (TextEditor == null) return;

        var selectionStart = TextEditor.SelectionStart;
        var selectionLength = TextEditor.SelectionLength;

        // 显示润色预览面板
        if (PolishPreviewPanel != null)
        {
            PolishPreviewPanel.Visibility = Visibility.Visible;
        }

        // 显示润色预览内容
        PolishPreview?.ShowPolishPreview(originalText, polishedText, selectionStart, selectionLength, useFloatingControl);
    }

    /// <summary>
    /// 隐藏润色预览
    /// </summary>
    public void HidePolishPreview()
    {
        if (PolishPreviewPanel != null)
        {
            PolishPreviewPanel.Visibility = Visibility.Collapsed;
        }
        PolishPreview?.HidePolishPreview();
    }

    /// <summary>
    /// 润色被接受事件处理
    /// </summary>
    private void PolishPreview_PolishAccepted(object? sender, PolishResultEventArgs e)
    {
        if (TextEditor != null)
        {
            // 替换选中的文本为润色后的文本
            TextEditor.Select(e.SelectionStart, e.SelectionLength);
            TextEditor.SelectedText = e.PolishedText;

            // 更新状态
            UpdateDocumentStatus("润色已应用");
        }

        // 隐藏润色预览面板
        HidePolishPreview();
    }

    /// <summary>
    /// 润色被拒绝事件处理
    /// </summary>
    private void PolishPreview_PolishRejected(object? sender, PolishResultEventArgs e)
    {
        // 保持原文不变，只更新状态
        UpdateDocumentStatus("已保留原文");

        // 隐藏润色预览面板
        HidePolishPreview();
    }

    /// <summary>
    /// 润色预览关闭事件处理
    /// </summary>
    private void PolishPreview_PreviewClosed(object? sender, EventArgs e)
    {
        HidePolishPreview();
    }

    #endregion

    #region 翻译扩写预览功能

    /// <summary>
    /// 显示翻译预览
    /// </summary>
    /// <param name="originalText">原文</param>
    /// <param name="translatedText">翻译后文本</param>
    /// <param name="useFloatingControl">是否使用悬浮控件</param>
    public void ShowTranslatePreview(string originalText, string translatedText, bool useFloatingControl = false)
    {
        if (TextEditor == null) return;

        var selectionStart = TextEditor.SelectionStart;
        var selectionLength = TextEditor.SelectionLength;

        // 隐藏润色预览面板
        HidePolishPreview();

        // 显示翻译扩写预览面板
        if (TranslateExpandPreviewPanel != null)
        {
            TranslateExpandPreviewPanel.Visibility = Visibility.Visible;
        }

        // 显示翻译预览内容
        TranslateExpandPreview?.ShowTranslatePreview(originalText, translatedText, selectionStart, selectionLength, useFloatingControl);
    }

    /// <summary>
    /// 显示扩写预览
    /// </summary>
    /// <param name="originalText">原文</param>
    /// <param name="expandedText">扩写后文本</param>
    /// <param name="useFloatingControl">是否使用悬浮控件</param>
    public void ShowExpandPreview(string originalText, string expandedText, bool useFloatingControl = false)
    {
        if (TextEditor == null) return;

        var selectionStart = TextEditor.SelectionStart;
        var selectionLength = TextEditor.SelectionLength;

        // 隐藏润色预览面板
        HidePolishPreview();

        // 显示翻译扩写预览面板
        if (TranslateExpandPreviewPanel != null)
        {
            TranslateExpandPreviewPanel.Visibility = Visibility.Visible;
        }

        // 显示扩写预览内容
        TranslateExpandPreview?.ShowExpandPreview(originalText, expandedText, selectionStart, selectionLength, useFloatingControl);
    }

    /// <summary>
    /// 隐藏翻译扩写预览
    /// </summary>
    public void HideTranslateExpandPreview()
    {
        if (TranslateExpandPreviewPanel != null)
        {
            TranslateExpandPreviewPanel.Visibility = Visibility.Collapsed;
        }
        TranslateExpandPreview?.HidePreview();
    }

    /// <summary>
    /// 翻译扩写被接受事件处理
    /// </summary>
    private void TranslateExpandPreview_ProcessAccepted(object? sender, ProcessResultEventArgs e)
    {
        if (TextEditor != null)
        {
            // 替换选中的文本为处理后的文本
            TextEditor.Select(e.SelectionStart, e.SelectionLength);
            TextEditor.SelectedText = e.ProcessedText;

            // 更新状态
            UpdateDocumentStatus($"{e.ProcessType}已应用");
        }

        // 隐藏预览面板
        HideTranslateExpandPreview();
    }

    /// <summary>
    /// 翻译扩写被拒绝事件处理
    /// </summary>
    private void TranslateExpandPreview_ProcessRejected(object? sender, ProcessResultEventArgs e)
    {
        // 保持原文不变，只更新状态
        UpdateDocumentStatus("已保留原文");

        // 隐藏预览面板
        HideTranslateExpandPreview();
    }

    /// <summary>
    /// 翻译扩写预览关闭事件处理
    /// </summary>
    private void TranslateExpandPreview_PreviewClosed(object? sender, EventArgs e)
    {
        // 隐藏预览面板
        HideTranslateExpandPreview();
    }

    #endregion

    #region 智能续写功能

    /// <summary>
    /// 获取当前章节细纲
    /// </summary>
    /// <returns>章节细纲内容</returns>
    public async Task<string> GetCurrentChapterOutlineAsync()
    {
        if (string.IsNullOrEmpty(_currentProjectPath))
            return string.Empty;

        try
        {
            // 尝试从文件名中提取章节号
            var fileName = Path.GetFileNameWithoutExtension(_currentFilePath ?? "");
            var chapterMatch = Regex.Match(fileName, @"第(\d+)章");

            if (chapterMatch.Success && int.TryParse(chapterMatch.Groups[1].Value, out int chapterNumber))
            {
                // 查找章节细纲文件，适应新的文件夹结构
                var possiblePaths = new[]
                {
                    // 新的文件夹结构：直接在大纲文件夹下查找
                    Path.Combine(_currentProjectPath, "大纲", $"*_第{chapterNumber:D3}章_*_章节细纲.txt"),
                    // 兼容旧的文件夹结构
                    Path.Combine(_currentProjectPath, "大纲", "章节", $"第{chapterNumber}章_细纲.txt"),
                    Path.Combine(_currentProjectPath, "大纲", "章节细纲", $"*_第{chapterNumber:D3}章_*_细纲.txt")
                };

                foreach (var pathPattern in possiblePaths)
                {
                    // 如果路径包含通配符，使用Directory.GetFiles查找
                    if (pathPattern.Contains("*"))
                    {
                        var directory = Path.GetDirectoryName(pathPattern);
                        var pattern = Path.GetFileName(pathPattern);
                        if (Directory.Exists(directory))
                        {
                            var files = Directory.GetFiles(directory, pattern);
                            if (files.Length > 0)
                            {
                                return await File.ReadAllTextAsync(files[0]);
                            }
                        }
                    }
                    else
                    {
                        // 直接检查文件是否存在
                        if (File.Exists(pathPattern))
                        {
                            return await File.ReadAllTextAsync(pathPattern);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"获取章节细纲失败: {ex.Message}");
        }

        return string.Empty;
    }

    /// <summary>
    /// 分析光标前的文本内容
    /// </summary>
    /// <param name="fullText">完整文本</param>
    /// <param name="caretOffset">光标位置</param>
    /// <returns>分析结果</returns>
    private (string PreviousContext, string LastSentence) AnalyzeContextForContinuation(string fullText, int caretOffset)
    {
        if (string.IsNullOrEmpty(fullText) || caretOffset <= 0)
            return (string.Empty, string.Empty);

        // 获取光标前的文本
        var previousText = fullText.Substring(0, Math.Min(caretOffset, fullText.Length));

        // 获取最后一段作为上下文（最多1000字符）
        var contextLength = Math.Min(1000, previousText.Length);
        var context = previousText.Substring(Math.Max(0, previousText.Length - contextLength));

        // 获取最后一句话
        var sentences = context.Split(new char[] { '。', '！', '？', '.', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
        var lastSentence = sentences.LastOrDefault()?.Trim() ?? "";

        return (context, lastSentence);
    }

    #endregion

    }
}
